package com.swx.identityservice.webapis;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swx.identityservice.dtos.scbpuser.InsertUserInputDto;
import com.swx.identityservice.dtos.scbpuser.UpdateUserInputDto;
import com.swx.identityservice.dtos.scbpuser.UserListOutputDto;
import com.swx.identityservice.dtos.scbpuser.UserOutputDto;
import com.swx.identityservice.models.ScbpDept;
import com.swx.identityservice.models.ScbpUser;
import com.swx.identityservice.models.UserNamePassword;
import com.swx.identityservice.service.LoginUser;
import com.swx.identityservice.service.ScbpDeptService;
import com.swx.identityservice.service.ScbpUserService;
import com.swx.identityservice.utils.JaxrsResponse;
import com.swx.identityservice.utils.ResponseMessages;
import com.swx.identityservice.utils.UploadUtils;
import com.swx.identityservice.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/*
 *@author:lxh
 * @controller: 用户控制器
 * */


@Slf4j
@Api(tags = "用户控制器")
@RestController
public class ScbpUserController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    private static final String INIT_PASSWORD = "123456";//添加用户的时候设置默认登录密码123456

    @Autowired
    private ScbpUserService scbpUserService;
    private ModelMapper modelMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ScbpDeptService scbpDeptService;

    public ScbpUserController() {
        modelMapper = new ModelMapper();
    }

    @ApiOperation("查询指定的用户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "userId", value = "用户id", required = true)
    })
    @GetMapping(value = "/getuser")
    @PreAuthorize("hasAuthority('Users_Select')")
    public JaxrsResponse get(@RequestParam("userId") int userId) {
        ScbpUser user = scbpUserService.selectByPrimaryKey(userId);
        UserOutputDto userOutputDto = modelMapper.map(user, UserOutputDto.class);

        return JaxrsResponse.builder().code(0).status("success").data(userOutputDto).build();
    }

    @ApiOperation("查询用户分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageIndex", value = "页码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "页容", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "Dept", value = "部门名称", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "Dept", value = "部门名称", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "WorkNum", value = "工作证号", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "UserName", value = "用户名", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "Account", value = "别名", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "PhoneNumber", value = "电话号码", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "Email", value = "邮箱", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "IdNumber", value = "身份证号码/军官证号码", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "cardtype", value = "身份类型", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "boolean", name = "IsInformal", value = "是否临时人员", required = false)})

    @GetMapping(value = "/getusers")
    @PreAuthorize("hasAuthority('Users_Select')")
    public JaxrsResponse get(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                             @RequestParam(value = "affiliateddept", required = false) String Affiliateddept,
                             String WorkNum, String UserName, String Account, String PhoneNumber, String Email,
                             String IdNumber, @RequestParam(value = "CardType", required = false) String cardtype, Boolean IsInformal) {
        PageHelper.startPage(pageIndex, pageSize);//分页
        List<ScbpUser> mapList = scbpUserService.selectAllWithOutDeletedByUserAndWorkNum(
                Affiliateddept, WorkNum, UserName, Account, PhoneNumber,
                Email, IdNumber, cardtype, IsInformal);//查询
        PageInfo<ScbpUser> pageInfo = new PageInfo<>(mapList);//分页查询
        UserListOutputDto listOutputDto = new UserListOutputDto();
        listOutputDto.setTotal(pageInfo.getTotal());
        for (int i = 0; i < pageInfo.getList().size(); i++) {
            UserOutputDto outputDto = modelMapper.map(mapList.get(i), UserOutputDto.class);
            List<Integer> roleids = new ArrayList<>();
            List<Integer> deptids = new ArrayList<>();
            String roleids1 = pageInfo.getList().get(i).getRoleids();
            String deptids1 = pageInfo.getList().get(i).getDeptids();

            String[] roleids2 = roleids1.split(",");
            String[] deptids2 = deptids1.split(",");
            for (String str : roleids2) {
                roleids.add(Integer.valueOf(str));
            }
            for (String s : deptids2) {
                deptids.add(Integer.valueOf(s));
            }
            outputDto.setDeptids(deptids);
            outputDto.setRoleids(roleids);
            listOutputDto.addUser(outputDto);
        }
        return JaxrsResponse.builder().code(0).status("success").data(listOutputDto).build();
    }

    /**
     * 递归查询顶级节点名称
     *
     * @param id
     * @return
     */
//    public String getTopName(Integer id) {
//        String str = "";
//        ScbpDept scbpDept = scbpDeptService.selectDeptById(id);
//        if (scbpDept.getPid() != 0) {//这就是出口
//            return getTopName(scbpDept.getPid());
//        } else {
//            str = scbpDept.getTitle();
//            return str;
//        }
//    }

    /**
     * 递归查询顶级节点id
     *
     * @param id
     * @return
     */
    public Integer getTopId(Integer id) {
        Integer topid = 0;
        ScbpDept scbpDept = scbpDeptService.selectDeptById(id);
        if (scbpDept.getPid() != 0) {//这就是出口
            return getTopId(scbpDept.getPid());
        } else {
            topid = scbpDept.getId();
            return topid;
        }
    }

    @ApiOperation("新增用户的同时，带头像")
    @PreAuthorize("hasAuthority('Users_Insert')")
    @PostMapping(value = "/adduser")
    public JaxrsResponse post(@Valid InsertUserInputDto scbpUserDto, @RequestParam(value = "avatorsrc") MultipartFile file) {
        if (scbpUserDto.getDeptids().length <= 0 && scbpUserDto.getRoleids().length <= 0) {
            return JaxrsResponse.builder().code(1).message(ResponseMessages.INSERT_NOT_COMPLETE).build();
        }
        ScbpUser scbpUser = modelMapper.map(scbpUserDto, ScbpUser.class);
        scbpUser.setCreationtime(new Date());
        Integer[] roldeids = scbpUserDto.getRoleids();
        Integer[] deptids = scbpUserDto.getDeptids();
        List<Integer> roldeids2 = Arrays.asList(roldeids);
        List<Integer> deptids2 = Arrays.asList(deptids);
        String roles = StringUtils.join(roldeids2, ",");
        String depts = StringUtils.join(deptids2, ",");
        scbpUser.setCreationtime(new Date());
        scbpUser.setDeptids(depts);//存放部门集合
        scbpUser.setRoleids(roles);//存放角色集合
        List<Integer> topidList = new ArrayList<>();
        for (int i = 0; i < deptids2.size(); i++) {
            ScbpDept scbpDept = scbpDeptService.selectByPrimaryKey(deptids2.get(i));
            Integer topId = getTopId(scbpDept.getId());
            topidList.add(topId);
        }
        scbpUser.setUnitids(StringUtils.join(topidList, ","));//存放单位集合
        String encode = bCryptPasswordEncoder.encode(INIT_PASSWORD);
        scbpUser.setPassword(encode);
        String avatorsrc = UploadUtils.Upload(file);
        scbpUser.setAvatorsrc(avatorsrc);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpUser.setCreatoruserid(loginUser.getId());
        int sr = scbpUserService.insertSelective(scbpUser);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.INSERT_FAIL).build();
    }

    @ApiOperation("新增用户的同时，第一次用户没有上传头像")
    @PreAuthorize("hasAuthority('Users_Insert')")
    @PostMapping(value = "/addusernotportrait")
    public JaxrsResponse post(@Valid InsertUserInputDto scbpUserDto) {
        if (scbpUserDto.getDeptids().length <= 0 && scbpUserDto.getRoleids().length <= 0) {
            return JaxrsResponse.builder().code(1).message(ResponseMessages.INSERT_NOT_COMPLETE).build();
        }
        ScbpUser scbpUser = modelMapper.map(scbpUserDto, ScbpUser.class);
        scbpUser.setCreationtime(new Date());
        Integer[] roldeids = scbpUserDto.getRoleids();
        Integer[] deptids = scbpUserDto.getDeptids();
        List<Integer> roldeids2 = Arrays.asList(roldeids);
        List<Integer> deptids2 = Arrays.asList(deptids);
        String roles = StringUtils.join(roldeids2, ",");
        String depts = StringUtils.join(deptids2, ",");
        scbpUser.setCreationtime(new Date());
        scbpUser.setDeptids(depts);//存放部门集合
        scbpUser.setRoleids(roles);//存放角色集合
        List<Integer> topidList = new ArrayList<>();

        for (int i = 0; i < deptids2.size(); i++) {
            ScbpDept scbpDept = scbpDeptService.selectByPrimaryKey(deptids2.get(i));
            Integer topId = getTopId(scbpDept.getId());
            topidList.add(topId);
        }
        scbpUser.setUnitids(StringUtils.join(topidList, ","));//存放单位集合
        String encode = bCryptPasswordEncoder.encode(INIT_PASSWORD);
        scbpUser.setPassword(encode);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpUser.setCreatoruserid(loginUser.getId());
        int sr = scbpUserService.insertSelective(scbpUser);
        if (sr > 0)
            return JaxrsResponse.builder().code(1).status("success").message(ResponseMessages.INSERT_SUCCESS).build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.INSERT_FAIL).build();
    }

    @ApiOperation("编辑用户,带头像")
    @PreAuthorize("hasAuthority('Users_Edit')")
    @PostMapping(value = "/edituser")
    public JaxrsResponse put(@Valid UpdateUserInputDto scbpUserDto, @RequestParam("avatorsrc") MultipartFile file) {
        if (scbpUserDto.getDeptids().length <= 0 && scbpUserDto.getRoleids().length <= 0) {
            return JaxrsResponse.builder().code(1).message(ResponseMessages.INSERT_NOT_COMPLETE).build();
        }
        ScbpUser scbpUser = modelMapper.map(scbpUserDto, ScbpUser.class);
        Integer[] roldeids = scbpUserDto.getRoleids();
        Integer[] deptids = scbpUserDto.getDeptids();
        List<Integer> roldeids2 = Arrays.asList(roldeids);
        List<Integer> deptids2 = Arrays.asList(deptids);
        String roles = StringUtils.join(roldeids2, ",");
        String depts = StringUtils.join(deptids2, ",");
        scbpUser.setLastmodificationtime(new Date());
        String avatarSrc = UploadUtils.Upload(file);
        scbpUser.setAvatorsrc(avatarSrc);
        scbpUser.setDeptids(depts);
        scbpUser.setRoleids(roles);
        scbpUser.setLastmodificationtime(new Date());
        List<Integer> topidList = new ArrayList<>();
        for (int i = 0; i < deptids2.size(); i++) {
            ScbpDept scbpDept = scbpDeptService.selectByPrimaryKey(deptids2.get(i));
            Integer topId = getTopId(scbpDept.getId());
            topidList.add(topId);
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpUser.setLastmodifieruserid(loginUser.getId());
        scbpUser.setUnitids(StringUtils.join(topidList, ","));//存放单位集合
        int sr = scbpUserService.updateByPrimaryKeySelective(scbpUser);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.UPDATE_FAIL).build();
    }

    @ApiOperation("编辑用户时用户没有上传头像")
    @PreAuthorize("hasAuthority('Users_Edit')")
    @PostMapping(value = "/editusernotportrait")
    public JaxrsResponse put(@Valid UpdateUserInputDto scbpUserDto) {
        if (scbpUserDto.getDeptids().length <= 0 && scbpUserDto.getRoleids().length <= 0) {
            return JaxrsResponse.builder().code(1).message(ResponseMessages.INSERT_NOT_COMPLETE).build();
        }

        ScbpUser scbpUser = modelMapper.map(scbpUserDto, ScbpUser.class);
        Integer[] roldeids = scbpUserDto.getRoleids();
        Integer[] deptids = scbpUserDto.getDeptids();
        List<Integer> roldeids2 = Arrays.asList(roldeids);
        List<Integer> deptids2 = Arrays.asList(deptids);
        String roles = StringUtils.join(roldeids2, ",");
        String depts = StringUtils.join(deptids2, ",");
        scbpUser.setDeptids(depts);
        scbpUser.setLastmodificationtime(new Date());
        scbpUser.setRoleids(roles);
        scbpUser.setLastmodificationtime(new Date());
        List<Integer> topidList = new ArrayList<>();
        for (int i = 0; i < deptids2.size(); i++) {
            ScbpDept scbpDept = scbpDeptService.selectByPrimaryKey(deptids2.get(i));
            Integer topId = getTopId(scbpDept.getId());
            topidList.add(topId);
        }
        scbpUser.setUnitids(StringUtils.join(topidList, ","));//存放单位集合
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpUser.setLastmodifieruserid(loginUser.getId());
        int sr = scbpUserService.updateByPrimaryKeySelective(scbpUser);
        if (sr > 0) {
            return JaxrsResponse.builder().code(0).status("success").build();
        }
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.UPDATE_FAIL).build();
    }

    @ApiOperation("删除用户")
    @DeleteMapping(value = "/deluser")
    @PreAuthorize("hasAuthority('Users_Delete')")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "userId", value = "用户id", required = true)
    })
    public JaxrsResponse delete(@RequestParam int userId) {
        ScbpUser scbpUser = new ScbpUser();
        scbpUser.setId(userId);
        scbpUser.setIsdeleted(true);
        scbpUser.setDeletiontime(new Date());
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpUser.setDeleteruserid(loginUser.getId());
        int sr = scbpUserService.updateByPrimaryKeySelective(scbpUser);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").data(scbpUser.getId()).build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.DELETE_FAIL).build();
    }

    @ApiOperation("用户修改密码")
    @PostMapping(value = "/updatePassword")
    public JaxrsResponse updatePassword(@RequestBody UserNamePassword loginUser) {

        ScbpUser scbpUser = scbpUserService.selectUserByName(loginUser.getUsername());
        if (scbpUser == null) return JaxrsResponse.builder().code(401).message("用户名不存在").build();
        ScbpUser scbpUser1 = modelMapper.map(loginUser, ScbpUser.class);
        boolean flag = bCryptPasswordEncoder.matches(loginUser.getOldpassword(), scbpUser.getPassword());
        log.info("flag==" + flag);
        if (!flag) {
            return JaxrsResponse.builder().code(200).status("fail").message("用户旧密码错误").build();
        }
        scbpUser1.setId(scbpUser.getId());
        String encode = bCryptPasswordEncoder.encode(loginUser.getPassword());
        scbpUser1.setPassword(encode);
        int i = scbpUserService.updateByPrimaryKeySelective(scbpUser1);
        if (i > 0) return JaxrsResponse.builder().code(0).status("success").build();
        return JaxrsResponse.builder().message("fail").build();
    }

    @ApiOperation("根据用户id查看该用户所有的权限信息,包含角色权限和个人权限")
    @GetMapping(value = "/getpermissionsbyuserid")
    public JaxrsResponse getpermissionsbyuserid(Integer id) {
        ScbpUser scbpUser = scbpUserService.selectByPrimaryKey(id);
        UserDetails userDetails = userDetailsService.loadUserByUsername(scbpUser.getUsername());
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        return JaxrsResponse.builder().status("success").data(authorities).build();
    }


    public static void main(String[] args) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123456");
        System.out.println(encode + "===1");
        String encode2 = bCryptPasswordEncoder.encode("123456");
        boolean matches2 = bCryptPasswordEncoder.matches("1234567", encode2);
        boolean matches = bCryptPasswordEncoder.matches("123456", encode);
        System.out.println(matches);
        System.out.println(matches2);
        System.out.println(encode2 + "===2");
    }


}
